﻿using AutoMapper;
using BW.MesProject.Equipment.Domain.Enum;
using BW.MesProject.Equipment.Domain.Equipment;
using BW.MesProject.Equipment.Infrastructure.Dto.Input.DeviceLedger;
using BW.MesProject.Equipment.Infrastructure.Dto.Output.DeviceLedger;
using BW.MesProject.Equipment.Infrastructure.Equipment;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.Equipment.Application.Equipment
{
    /// <summary>
    /// 设备台账服务实现层
    /// </summary>
    public class DeviceLedgerService : IDeviceLedgerService
    {
        private readonly IBaseRepository<DeviceLedgerModel> _deviceLedgerRepository;
        private readonly IMapper _mapper;
        private readonly IBaseRepository<DeviceTypeModel> _deviceTypeRepository;

        public DeviceLedgerService(IBaseRepository<DeviceLedgerModel> DeviceLedgerRepository, IMapper mapper, IBaseRepository<DeviceTypeModel> DeviceTypeRepository)
        {
            _deviceLedgerRepository = DeviceLedgerRepository;
            this._mapper = mapper;
            _deviceTypeRepository = DeviceTypeRepository;
        }

        /// <summary>
        /// 获取设备类型信息
        /// </summary>
        /// <returns></returns>
        public ApiResult<List<DeviceTypeModel>> GetDeviceTypeValue()
        {
            //根据设备类型编号获取设备类型未删除的数据
            var deviceTypeModel = _deviceTypeRepository.GetAll().Where(x => x.IsDeleted == false);

            if (deviceTypeModel == null)
            {
                return new ApiResult<List<DeviceTypeModel>>
                {
                    Code = ApiEnums.Success,
                    Message = "未获取到设备类型信息",
                };
            }
            return new ApiResult<List<DeviceTypeModel>>
            {
                Code = ApiEnums.Success,
                Message = "获取设备类型信息成功",
                Data = deviceTypeModel.ToList(),
            };
        }

        /// <summary>
        /// 添加设备台账
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> AddDeviceLedger(AddDeviceLedgerInput input)
        {
            var data = _mapper.Map<DeviceLedgerModel>(input);
            //判断设备台账名称是否已存在
            var res = _deviceLedgerRepository.GetValue(x => x.DeviceLedgerName == input.DeviceLedgerName);
            if (res != null)  
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "设备台账名称已存在",
                    Data = 0
                };
            }
            //生成设备台账id
            data.Id = YitIdHelper.NextId();
            //生成设备台账编号：DL+年月日+4位随机数
            var newCode = "DL" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999);
            data.DeviceLedgerCode = newCode;
            //生成资产编号：BWAN+年月日+4位随机数
            var newAssetNumber = "BWAN" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999);
            data.AssetNumber = newAssetNumber;
            //生成设备台账序列号：SN+年月日+4位随机数
            var newSerialNum = "SN" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999);
            data.DeviceLedgerSerialNum = newSerialNum;

            var result = _deviceLedgerRepository.Add(data);
            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Message = "添加设备台账成功",
                Data = result
            };
        }

        /// <summary>
        /// 获取设备台账列表  
        /// </summary>
        /// <param name="input">设备台账查询输入参数</param>
        /// <returns>分页后的设备台账输出参数列表</returns>
        public ApiPaging<DeviceLedgerOutput> GetDeviceLedgerList(DeviceLedgerQueryInput input)
        {
            // 获取未被逻辑删除的设备台账数据
            var ledgerList = _deviceLedgerRepository.GetAll().Where(x => !x.IsDeleted);

            // 条件过滤：根据输入参数进行模糊或精确查询
            if (!string.IsNullOrEmpty(input.DeviceLedgerSerialNum))
            {
                // 按设备序列号精确查询
                ledgerList = ledgerList.Where(x => x.DeviceLedgerSerialNum == input.DeviceLedgerSerialNum);
            }
            if (!string.IsNullOrEmpty(input.DeviceLedgerCode))
            {
                // 按设备台账编号精确查询
                ledgerList = ledgerList.Where(x => x.DeviceLedgerCode == input.DeviceLedgerCode);
            }
            if (!string.IsNullOrEmpty(input.DeviceLedgerName))
            {
                // 按设备名称模糊查询
                ledgerList = ledgerList.Where(x => x.DeviceLedgerName.Contains(input.DeviceLedgerName));
            }

            // 联表查询设备类型，获取设备类型名称等信息
            var query = ledgerList.LeftJoin<DeviceTypeModel>((a, b) => a.DeviceTypeId == b.Id && !b.IsDeleted).Select((a, b) =>
                 new DeviceLedgerOutput
                 {
                     Id = a.Id, // 设备台账Id
                     AssetNumber = a.AssetNumber, // 资产编号
                     DeviceLedgerSerialNum = a.DeviceLedgerSerialNum, // 设备序列号
                     DeviceLedgerCode = a.DeviceLedgerCode, // 设备编码
                     DeviceLedgerName = a.DeviceLedgerName, // 设备名称
                     DeviceStatues = a.DeviceStatues, // 设备状态
                     DeviceSpeciFication = a.DeviceSpeciFication, // 设备规格
                     DeviceType = a.DeviceType, // 设备型号
                     DeviceBrand = a.DeviceBrand, // 设备品牌
                     DeviceNum = a.DeviceNum, // 设备数量
                     DeviceBeginTime = a.DeviceBeginTime, // 生产日期
                     DeviceEnterTime = a.DeviceEnterTime, // 入场时间
                     SupplierId = a.SupplierId, // 供应商Id
                     WorkShopId = a.WorkShopId, // 车间Id
                     Devicelocation = a.Devicelocation, // 位置
                     DeviceuseDepartments = a.DeviceuseDepartments, // 使用部门
                     DeviceHead = a.DeviceHead, // 负责人
                     DeviceRemark = a.DeviceRemark, // 备注
                     DeviceTypeId = b.Id, // 设备类型Id
                     DeviceTypeName = b.DeviceTypeName, // 设备类型名称
                     CreatedBy = a.CreatedBy, // 创建人
                     CreatedTime = a.CreatedTime, // 创建时间
                     UpdatedTime = a.UpdatedTime, // 修改时间
                 });
          
            // 分页处理：按Id倒序排列，跳过前面页数的数据，取当前页数据
            var pageData = query
                .OrderByDescending(a => a.Id)
                .Skip((input.PageIndex - 1) * input.PageSize)
                .Take(input.PageSize)
                .ToList();
            // 在获取分页数据后添加
            foreach (var item in pageData)
            {
                // 将int转为枚举再获取描述
                if (Enum.IsDefined(typeof(DeviceStatus), item.DeviceStatues))
                {
                    var status = (DeviceStatus)item.DeviceStatues;
                    item.DeviceStatusText = status.ToString(); // 或使用 status.GetDescription() 获取自定义描述
                }
                else
                {
                    item.DeviceStatusText = "未知状态";
                }
            }

            // 返回分页结果
            return new ApiPaging<DeviceLedgerOutput>
            {
                Code = ApiEnums.Success,
                Message = "获取设备台账列表成功",
                TotalCount = query.Count(), // 总条数
                PageData = pageData // 当前页数据
            };
        }

        /// <summary>
        /// 根据设备台账获取设备台账数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<DeviceLedgerOutput> GetDeviceLedgerValue(long id)
        {
            var ledgerList = _deviceLedgerRepository.GetValue(x => x.Id == id);
            if (ledgerList == null)
            {
                return new ApiResult<DeviceLedgerOutput>
                {
                    Code = ApiEnums.Success,
                    Message = "您要修改的设备台账信息不存在"
                };
            }
            var data = _mapper.Map<DeviceLedgerOutput>(ledgerList);
            return new ApiResult<DeviceLedgerOutput>
            {
                Code = ApiEnums.Success,
                Message = "获取设备台账信息成功",
                Data = data
            };
        }

        /// <summary>
        /// 修改设备台账
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDeviceLedger(UpdateDeviceLedgerInput input)
        {
            //根据设备台账Id获取设备台账数据
            var ledgerModel = _deviceLedgerRepository.GetValue(x => x.Id == input.Id);
            if (ledgerModel == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "您要修改的设备台账信息不存在",
                    Data = 0
                };
            }
            ledgerModel = _mapper.Map(input, ledgerModel);
            ledgerModel.UpdatedTime = DateTime.Now;

            //判断设备台账名称是否已存在
            var ledgerName = _deviceLedgerRepository.GetValue(x => x.DeviceLedgerName == input.DeviceLedgerName);
            if (ledgerName != null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "设备台账名称已存在",
                    Data = 0
                };
            }
            //更新设备台账数据
            var res=_deviceLedgerRepository.Update(ledgerModel);
            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Message = "修改设备台账信息成功",
                Data = res
            };
        }


        /// <summary>
        /// 删除设备台账
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<int> DeleteDeviceLedger(long id)
        {
            //根据设备台账Id获取设备台账数据
            var ledgerModel = _deviceLedgerRepository.GetValue(x => x.Id == id);
            if (ledgerModel == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "您要删除的设备台账信息不存在",
                    Data = 0
                };
            }
            ledgerModel.IsDeleted = true; // 设置为已删除
            ledgerModel.UpdatedTime = DateTime.Now; // 更新修改时间
            //更新设备台账数据
            var res=_deviceLedgerRepository.Update(ledgerModel);
            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Message = "删除设备台账信息成功",
                Data = res
            };
        }
    }
}